import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:family_app/src/features/finance/models/monthly_bill_model.dart';
import 'package:family_app/src/features/finance/providers/finance_provider.dart';
import 'package:family_app/src/theme/app_theme.dart';

/// 月度账单列表组件
class MonthlyBillList extends ConsumerWidget {
  /// 年份
  final int year;

  /// 用户ID
  final int userId;

  /// 构造函数
  const MonthlyBillList({
    Key? key,
    required this.year,
    required this.userId,
  }) : super(key: key);

  @override
  Widget build(BuildContext context, WidgetRef ref) {
    // 监听年度账单列表数据
    final monthlyBillsAsync = ref.watch(yearlyBillListProvider((year, userId)));

    return monthlyBillsAsync.when(
      data: (monthlyBills) {
        // 如果没有数据，显示空状态
        if (monthlyBills.isEmpty) {
          return _buildEmptyState();
        }

        // 按月份排序
        final sortedBills = List<MonthlyBillModel>.from(monthlyBills)
          ..sort((a, b) => int.parse(a.month).compareTo(int.parse(b.month)));

        return Column(
          children: [
            // 列表标题
            Padding(
              padding: EdgeInsets.symmetric(horizontal: 16.w, vertical: 12.h),
              child: Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children:
                    [Text('$year年账单概览', style: TextStyle(fontSize: 16.sp, fontWeight: FontWeight.bold)),
                  Text('共${sortedBills.length}个月', style: TextStyle(fontSize: 14.sp, color: AppTheme.textSecondaryColor)),
                ],
              ),
            ),

            // 账单列表
            Expanded(
              child: ListView.builder(
                padding: EdgeInsets.symmetric(horizontal: 16.w),
                itemCount: sortedBills.length,
                itemBuilder: (context, index) {
                  final bill = sortedBills[index];
                  return _buildBillItem(context, bill);
                },
              ),
            ),
          ],
        );
      },
      loading: () => const Center(child: CircularProgressIndicator()),
      error: (error, stack) => Center(
        child: Text('加载账单失败: $error', style: TextStyle(color: Colors.red)),
      ),
    );
  }

  /// 构建单个账单条目
  Widget _buildBillItem(BuildContext context, MonthlyBillModel bill) {
    return Container(
      margin: EdgeInsets.only(bottom: 12.h),
      padding: EdgeInsets.all(16.w),
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(12.r),
        boxShadow: [
          BoxShadow(
            color: Colors.grey.withOpacity(0.1),
            spreadRadius: 2,
            blurRadius: 4,
            offset: const Offset(0, 2),
          ),
        ],
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children:
            [Text(bill.formattedMonth, style: TextStyle(fontSize: 16.sp, fontWeight: FontWeight.bold, color: AppTheme.textPrimaryColor)),
          SizedBox(height: 12.h),
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              // 支出信息
              Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Text('支出', style: TextStyle(fontSize: 14.sp, color: AppTheme.textSecondaryColor)),
                  SizedBox(height: 4.h),
                  Text(bill.formattedExpense, style: TextStyle(fontSize: 18.sp, fontWeight: FontWeight.bold, color: Colors.red)),
                ],
              ),

              // 收入信息
              Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Text('收入', style: TextStyle(fontSize: 14.sp, color: AppTheme.textSecondaryColor)),
                  SizedBox(height: 4.h),
                  Text(bill.formattedIncome, style: TextStyle(fontSize: 18.sp, fontWeight: FontWeight.bold, color: Colors.green)),
                ],
              ),

              // 操作按钮
              IconButton(
                icon: const Icon(Icons.chevron_right, color: AppTheme.textSecondaryColor),
                onPressed: () {
                  // 点击事件，可以跳转到月度详情页
                  _onBillItemTap(context, bill);
                },
              ),
            ],
          ),
        ],
      ),
    );
  }

  /// 构建空状态界面
  Widget _buildEmptyState() {
    return Center(
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          Icon(Icons.receipt_long_outlined, size: 64.r, color: Colors.grey),
          SizedBox(height: 16.h),
          Text(
            '暂无账单记录',
            style: TextStyle(fontSize: 16.sp, color: Colors.grey),
          ),
          SizedBox(height: 8.h),
          Text(
            '$year年暂无账单数据',
            style: TextStyle(fontSize: 14.sp, color: AppTheme.textSecondaryColor),
          ),
        ],
      ),
    );
  }

  /// 账单条目点击处理
  void _onBillItemTap(BuildContext context, MonthlyBillModel bill) {
    // 这里可以实现点击跳转到月度详情页的逻辑
    // 例如：
    // Navigator.push(
    //   context,
    //   MaterialPageRoute(
    //     builder: (context) => MonthlyBillDetailPage(
    //       yearMonth: bill.yearMonth,
    //     ),
    //   ),
    // );
    ScaffoldMessenger.of(context).showSnackBar(
      SnackBar(content: Text('查看${bill.formattedMonth}详情')),
    );
  }
}